import { runIntervally } from '@/utils/functions/inInterval';

/**
 * 历史累计的 CPU 使用量
 */
const historyCPU: number[] = [];
const HISTORY_LIMIT = 25;

function recordCPU() {
    if (historyCPU.length >= HISTORY_LIMIT) {
        historyCPU.shift();
    }
    historyCPU.push(Game.cpu.getUsed());
}

export function collectStatistics() {
    // 初始化储存
    Memory.stats ??= {} as any;
    recordCPU();
    // 定期执行
    runIntervally(IntervalLength.short, () => {
        // 全局信息
        Memory.stats.gclLevel = Game.gcl.level;
        Memory.stats.gplLevel = Game.gcl.level;
        Memory.stats.gclProgress = Game.gcl.progress / Game.gcl.progressTotal;
        Memory.stats.gplProgress = Game.gpl.progress / Game.gpl.progressTotal;
        // CPU
        Memory.stats.cpu = historyCPU.sum() / historyCPU.length;
        Memory.stats.bucket = Game.cpu.bucket;
        // 市场
        Memory.stats.credits = Game.market.credits;
        // 房间统计
        if (!Memory.stats.rooms) {
            Memory.stats.rooms = {};
        }
        Object.values(Empire.colonies).forEach(colony => {
            const c = colony.capital.getController();
            const s = colony.capital.getStorage();
            const t = colony.capital.getTerminal();
            Memory.stats.rooms[colony.name] = {
                rcl: c.level,
                rclProgress: c.progress / c.progressTotal,
                energy: c.level < 4 ? 0 : s.store.energy,
                storageUsed: c.level < 4 ? 0 : s.store.getUsedCapacity() / s.store.getCapacity(),
                totalPower: (c.level < 4 ? 0 : s.store.power) + (c.level < 6 ? 0 : t.store.power)
            };
        });
    });
}